<template lang="pug">
.role-manage-power
  el-dialog(title="权限设置" v-model="dialogVisible" @close="handleClose" custom-class="dialog-width")
    .table-power-wrap
      .btn-list
        el-button(type='primary' size='small' @click='expandedUp' style='margin-rgiht: 20px;') 全部展开
        el-button(type='primary' size='small' @click='expandedDown') 全部收起

      el-scrollbar.scrollbar-dialog-wrap
        el-checkbox-group(v-model="state.permissionIds")
          el-table(:data="formatData()" border='border' :row-style="isRow" v-loading="tableLoading")
            el-table-column(label='模块名')
              template(#default="scope")
                span.tree-space(v-for='space in scope.row._level' :key='space')
                span.tree-ctrl(v-if='iconShow(0, scope.row)' @click='toggleExpanded(scope.$index)')
                  i.el-icon-plus(v-if='!scope.row._isExpand')
                  i.el-icon-minus(v-else)
                el-checkbox(:label='scope.row.id' :key="scope.row.id" v-if='scope.row.childList' v-bind='{disabled: checkParentFun(scope.row.parentId, scope.row.id)}') {{scope.row.permissionName}}

    .ti-text 温馨提示：在分配或移除权限后，需要点击确定按钮，权限分配才能成功。

    .dialog-footer
      el-button(@click="formSubmit" type="primary" size="small" :lodading="loading") 确定
      el-button(@click="handleClose" type="danger" size="small") 取消
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch, defineProps, defineEmit } from 'vue'

import initTreeArray from './eval'

const { proxy } = getCurrentInstance()
const emit = defineEmit(['closeFun', 'update:isDialog'])
const props = defineProps({
  isDialog: {
    required: true
  },
  dialogRecord: {
    required: true
  }
})

const state = reactive({
  listData: [],
  permissionIds: []
})
const dialogVisible = ref(false)
const tableLoading = ref(false)
const loading = ref(false)

// 侦听
watch(() => [props.isDialog], ([newDialog, oldDialog]) => {
  if (!newDialog) return

  dialogVisible.value = newDialog
}, { immediate: true })

getModuleList()

// 展开
function expandedUp () {
  formatData().forEach(scope => {
    scope._isExpand = true
  })
}

// 收起
function expandedDown () {
  formatData().forEach(scope => {
    scope._isExpand = false
  })
}

// 初始化表格数据
function formatData () {
  let arr = []
  if (!Array.isArray(state.listData)) {
    arr = []
  } else {
    arr = [].concat(state.listData)
  }
  const args = [].concat([arr, false])
  return initTreeArray.apply(null, args)
}

// 给行设置样式
function isRow (row) {
  const show = row.row.parent ? row.row.parent._isExpand && row.row.parent._show : true
  row.row._show = show
  return show ? { animation: 'treeTableShow 1s', '-webkit-animation': 'treeTableShow 1s' } : { display: 'none' }
}

// 判断是否可以选择
function checkParentFun (parentId, id) {
  if (parentId === 0) return false
  if (state.permissionIds.indexOf(parentId) < 0) {
    const index = state.permissionIds.indexOf(id)
    if (index > -1) {
      state.permissionIds.splice(index, 1)
    }
    return true
  }
  return false
}

// 判断是否存在自己,存在展示 icon
function iconShow (index, scope) {
  return index === 0 && scope.childList && scope.childList.length > 0
}

// 子级展开或收起
function toggleExpanded (clkIndex) {
  const scope = formatData()[clkIndex]
  scope._isExpand = !scope._isExpand
}

// 表达提交
function formSubmit () {
  loading.value = true
  proxy.$message({ type: 'success', message: '提交成功' })
  emit('closeFun')
  handleClose()
}

// 获取模块列表
function getModuleList () {
  state.listData = [{
    id: 1,
    parentId: 0,
    permissionName: 'vue3.0 权限管理',
    childList: [
      {
        id: 2,
        parentId: 1,
        permissionName: '系统管理',
        childList: [
          {
            id: 3,
            parentId: 2,
            permissionName: '用户管理',
            childList: [
              { id: 4, parentId: 3, permissionName: '用户管理-添加', childList: [] }
            ]
          },
          { id: 5, parentId: 2, permissionName: '角色管理', childList: [] },
          { id: 6, parentId: 2, permissionName: '模块管理', childList: [] }
        ]
      },
      {
        id: 7,
        parentId: 1,
        permissionName: '落地页管理',
        childList: [
          { id: 8, parentId: 7, permissionName: '落地页列表', childList: [] }
        ]
      }
    ]
  }]
  state.permissionIds = [1, 2, 3, 4, 5, 6]
}

// 关闭弹窗
function handleClose () {
  emit('update:isDialog', false)
  dialogVisible.value = false
}
</script>
<style rel="stylesheet/scss" lang="scss">
  .role-manage-power {
    .tree-space {
      display: inline-block;
      width: 14px;
      height: 14px;
    }
    .tree-ctrl {
      position: relative;
      display: inline-block;
      margin-left: -14px;
      margin-right: 5px;
      z-index: 2;
      width: 14px;
      cursor: pointer;
      i {
        color: #409eff;
      }
    }
    .btn-list {
      margin-bottom: 10px;
    }
    .ti-text {
      color: blue;
      padding: 10px 0;
    }
  }
</style>
